javascript:(function() {
	/*
	New script to parse the Inventory that Zynga now provides good info on in the code.
	There is a lot of interesting information in the code, like FreeGiftable (bool)
	
	Suggestions: http://www.facebook.com/topic.php?uid=92178514356&topic=24399
	Support: http://www.facebook.com/topic.php?uid=92178514356&topic=24414
	
	(c) Spockholm Mafia Tools http://www.spockholm.com/mafia/help.php
	
	Credits:
	Proper suggestion count function, The Coroner @ http://www.mafiacontrolled.com/
	
	Changelog:
	2011-01-17	v1.04	function find_improvements
	2011-01-18			Change header for Not-Using lists
	2011-01-19	v1.05	Add quality icon to items
						Statistics on item Quality
	2011-01-20	v1.06	David Van Ginneken added top 5 limit option for not using
	2011-01-26	v1.07	Showing all suggestions, including not owned items.
						slideDown and slideup animations used for showing/hiding the suggestions.
	2011-02-22	v1.08	Added popup of all the inventory, sorted by attack or defense
	2011-03-16	v1.09	Fixed after Brazil changes.
	*/

	function unframeMW() {
		if (document.getElementsByClassName('canvas_iframe_util')[0]) {
			window.location.href=document.getElementsByClassName('canvas_iframe_util')[0].src;
			return;
		}
		else {
			document.body.parentNode.style.overflowY="scroll";
			document.body.style.overflowX="auto";
			document.body.style.overflowY="auto";
			try {
				document.evaluate('//div[@id="mw_city_wrapper"]/div',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null).snapshotItem(0).style.margin="auto";
				if(typeof FB != 'undefined') {
					FB.CanvasClient.stopTimerToSizeToContent; 
					window.clearInterval(FB.CanvasClient._timer);
					FB.CanvasClient._timer=-1;
				}
				document.getElementById('mw_zbar').parentNode.removeChild(document.getElementById('mw_zbar'));
				document.getElementById('snapi_zbar').parentNode.parentNode.removeChild(document.getElementById('snapi_zbar').parentNode);
			}
			catch (fberr) {}
			//Revolving Revolver of Death from Arun, http://arun.keen-computing.co.uk/?page_id=33
			$('#LoadingBackground').hide();
			$('#LoadingOverlay').hide();
			$('#LoadingRefresh').hide();
		}
	}
	unframeMW();

	var version = '<a href="http://www.spockholm.com/mafia/testing.php">Spockholm</a> Item Analyzer v1.09 beta'
	head = '',
	body = '',
	tail = '',
	Items = [], Qualities = {}, Locations = {}, Subtypes = {}, ItemTypes = {}, cityCashImg = {}, QualityHave = [],
	mafiasize = 501,
	attack_total = 0, defense_total = 0;
	weapons_attack_total = 0, weapons_defense_total = 0,
	armor_attack_total = 0, armor_defense_total = 0,
	vehicles_attack_total = 0, vehicles_defense_total = 0,
	animals_attack_total = 0, animals_defense_total = 0,
	analyze = [],
	analyze_dupecheck = '',
	debugoutput = true;

	var stopimg = '';
	
	//quick hack to remove the colliding text if launched on inventory page
	$('.tip_box').remove();
	
	function commas(s) {
		while (d=/(-)?(\d+)(\d{3}.*)/.exec(s)) {
			s = (d[1]?d[1]+d[2]+','+d[3]:d[2]+','+d[3]);
		}
		return s;
	}
	function find_improvements(m_value, category, c_type) {
		// m_value: is the numerical atk/def value of the item we are seeing for the improvement for..
		// category: is attack or defense
		// type: 1-4 (itemtype == 'Weapons' || itemtype == 'Armor' || itemtype == 'Vehicles' || itemtype == 'Animals'
		// Loop through all currently used items..
		var i_count = 0;
		var i_value = 0;
		var t_item_count = 0;
		var t_item_improvement = 0;
		for (l in Items) {
            if (Items[l].type  == c_type && ((category == 'attack' && Items[l].equipped_offense > 0 && Items[l].attack < m_value)||(category == 'defense' && Items[l].equipped_defense > 0 && Items[l].defense < m_value))) {
				//  We have an equipped item, less than the value we are checking..
				if (category == 'attack') {
						i_count = parseInt(Items[l].equipped_offense);
						i_value = parseInt(Items[l].attack);
				}
				if (category == 'defense') {
						i_count = parseInt(Items[l].equipped_defense);
						i_value = parseInt(Items[l].defense);
				}
				// The count of currently equipped items.. times the difference in the value
				t_item_count = t_item_count + i_count;
 				t_item_improvement = t_item_improvement + (i_count*(m_value - i_value));
			}
		}
		return [t_item_count, t_item_improvement];
	}
	function writeTable(sortby,header,own,type,limit) {
		function customSort(property) {
			return function (b, a) {
				return parseInt(a[property]) - parseInt(b[property]);
			};
		}
		if (typeof sortby == 'string') { //only sort if we get a string
			Items.sort(customSort(sortby));
		}
		var count = 0;
		var zebra = 0;
		if (limit == null){ limit = -1;}
		body += '<table class="messages">\n';
		if (own && !(/NotUsing/.test(type))) {
			//only owned items and using, include the quality have row
			body += '<tr><td colspan="'+(sortby == 'combined'?'9':'8')+'" id="'+header+'">Quality Row</td></tr>';
			body += '<tr><td colspan="'+(sortby == 'combined'?'9':'8')+'"><div id="'+header+'_bar">Quality Bar</div></td></tr>';
		}
		body += '<tr><th colspan="2"><h3 class="good">Top '+header+'</h3></th><th>Attack:</th><th>Defense:</th>'+((sortby == 'combined')?'<th>Combined:</th>':'')+'<th>'+(/NotUsing/.test(type)?'Not Using:</th>':'Using:</th><th>Have:</th>')+'<th>Location:</th><th>Giftable:</th></tr>';
		for (x in Items) {
			var wishlist = '';
			if (Items[x].tradeable == '1') {
				if(giftable = /gift_category=(\d+).*?gift_id=(\d+)/.exec(Items[x].gift_link)) {
					//wishlist = '[<a href="http://apps.facebook.com/inthemafia/track.php?next_controller=wishlist&next_action=add&next_params=%7B%22gift_category%22%3A%22'+giftable[1]+'%22%2C%22gift_id%22%3A%22'+giftable[2]+'%22%7D">Add to Wishlist</a>]';
					if (Items[x].wishlist) {
						wishlist = '[On Wishlist]';
					}
					else {
						var onclick = 'WishlistController.addLoot('+Items[x].id+'); return false;';
						wishlist = '[<a href="#" onclick="'+onclick+'">Add to Wishlist</a>]';
					}
					//do_ajax('inner_page','Items[x].gift_link',1,0,0,0);";
					//do_ajax('inner_page','"+itemData['gift_link']+"',1,0,0,0);
					var onclick = "do_ajax('inner_page','"+Items[x].gift_link+"',1,1,0,0);";
					wishlist += ' [<a href="#" onclick="'+onclick+'">Send Gift</a>]';
				}
				else {
					wishlist = 'Missing data in Zynga DB';
				}
			}
			var location = 'Unknown', locationtext = '';
			if (typeof Items[x].location == 'number') {
				locationtext = Locations[Items[x].location+''].name;
				//locationtext = '<a href="'+Locations[Items[x].location+''].link+'">'+Locations[Items[x].location+''].name+'</a>';
			}
			var itemtype = 'Unknown';
			if (typeof Items[x].type == 'number') {
				itemtype = ItemTypes[Items[x].type+''];
			}
			var using = 0;
			var max_using = 0;
			// Get the maximum used for this item, whether it be on attack side or defense side..
			max_using = (parseInt(Items[x].equipped_offense)> parseInt(Items[x].equipped_defense)? parseInt(Items[x].equipped_offense): parseInt(Items[x].equipped_defense)); 
			if (sortby == 'attack') {
				using = parseInt(Items[x].equipped_offense);
			}
			if (sortby == 'defense') {
				using = parseInt(Items[x].equipped_defense);
			}
			if (sortby == 'combined') {
				//using = parseInt(Items[x].equipped_offense+Items[x].equipped_defense);
				//using = Items[x].quantity;
				using = (count+Items[x].quantity)>mafiasize?mafiasize-count:Items[x].quantity;
			}
			if (itemtype == type) { //type is matched
				if (itemtype == 'Weapons' || itemtype == 'Armor' || itemtype == 'Vehicles' || itemtype == 'Animals') { //top 501 Weapon, Armor, Vehicle or Animal only
					var i_count = 0;
					var i_improve = 0;	
					var i_improvement = [];

					i_improvement = find_improvements(Items[x][sortby],sortby,Items[x].type);
					if ((Items[x].tradeable == 1) && (i_improvement[0] > 0)) {
						//analyze[analyze.length] = '<div name="'+Locations[Items[x].location+''].name+'">['+itemtype+'] <span class="good">'+i_improvement[0]+'x</span> '+Items[x].name+' for '+sortby+' increase: <span class="good">'+commas(i_improvement[1])+'</span>. Source: '+Locations[Items[x].location+''].name+' or gift.'+'</div>';
						if (analyze_dupecheck.search(Items[x].name) < 0) {
							analyze[analyze.length] = '<div name="Gifting">['+itemtype+'] <span class="good">'+i_improvement[0]+'x</span> '+Items[x].name+' for '+sortby+' increase: <span class="good">'+commas(i_improvement[1])+'</span>. Source: '+Locations[Items[x].location+''].name+' or gift.'+'</div>';
							analyze_dupecheck += Items[x].name+'|';
							//console.log(analyze_dupecheck);
						}
					}
					if (Items[x].purchasable && (i_improvement[0] > 0)) {
						if (analyze_dupecheck.search(Items[x].name) < 0) {
							analyze[analyze.length] = '<div name="'+Locations[Items[x].location+''].name+'">['+itemtype+'] <span class="good">'+i_improvement[0]+'x</span> '+Items[x].name+' ('+Items[x].formated_price.substr(0,2)+''+commas((i_improvement[0])*Items[x].cash_price)+') for '+sortby+' increase: <span class="good">'+commas(i_improvement[1])+'</span>. Source: Buy in '+Locations[Items[x].location+''].name+'</div>';
							analyze_dupecheck += Items[x].name+'|';
						}
					}
					if ((Items[x].rp_price > 0) && (i_improvement[0] > 0)) {
						if (analyze_dupecheck.search(Items[x].name) < 0) {
							analyze[analyze.length] = '<div name="'+Locations[Items[x].location+''].name+'">['+itemtype+'] <span class="good">'+i_improvement[0]+'x</span> '+Items[x].name+' (RP: '+commas(i_improvement[0]*Items[x].rp_price)+') for '+sortby+' increase: <span class="good">'+commas(i_improvement[1])+'</span>. Source: Buy in '+Locations[Items[x].location+''].name+'</div>';
							analyze_dupecheck += Items[x].name+'|';
						}
					}
					if ((Items[x].rp_price == 0) && !Items[x].purchasable && (Items[x].tradeable == 0) && (Items[x].location == 9) && Items[x].active && (i_improvement[0] > 0)) {
						if (analyze_dupecheck.search(Items[x].name) < 0) {
							analyze[analyze.length] = '<div name="'+Locations[Items[x].location+''].name+'">['+itemtype+'] <span class="good">'+i_improvement[0]+'x</span> '+Items[x].name+' (RP: '+commas(i_improvement[0]*Items[x].rp_price)+') for '+sortby+' increase: <span class="good">'+commas(i_improvement[1])+'</span>. Source: Buy in '+Locations[Items[x].location+''].name+'</div>';
							analyze_dupecheck += Items[x].name+'|';
						}
					}
					if ((using > 0) && Items[x].active && own) { //list only using, active and owned items
						body += '<tr style="background-color:'+(zebra%2?'#000000':'#202020')+'">\
						<td>'+Qualities[Items[x].quality+''].image+'</td>\
						<td>'+Items[x].name+'</td>\
						<td>'+Items[x].attack+'</td>\
						<td>'+Items[x].defense+'</td>'
						+(sortby == 'combined'?'<td colspan="2">'+Items[x].combined+'</td>':(count+using)>mafiasize?'<td>'+mafiasize-count+'</td>':'<td>'+using+'</td>')+
						'<td>'+Items[x].quantity+'</td>\
						<td>'+locationtext+'</td>\
						<td>'+wishlist+'</td></tr>\n';
						
						count += parseInt(using);
						if (typeof QualityHave[itemtype] != 'object') {
							QualityHave[itemtype] = {};
							QualityHave[itemtype].Common = 0;
							QualityHave[itemtype].Uncommon = 0;
							QualityHave[itemtype].Rare = 0;
							QualityHave[itemtype].Superior = 0;
							QualityHave[itemtype].Ultimate = 0;
							QualityHave[itemtype].total = 0;
						}
						QualityHave[itemtype][Qualities[Items[x].quality+''].name] += parseInt(using);
						QualityHave[itemtype].total += parseInt(using);
						//Analyze of inventory needs to check for next item to fix this problem
						//Reinhardt and Otto 57 36 84/392
						//Thermal Shielding 57 30 1/1
						//Pantomime Horse 57 31 4/4
						//[Armor] 5x Reinhardt and Otto for attack increase: 285. Source: Las Vegas or gift.
						zebra++;
						attack_total += parseInt(Items[x].equipped_offense*Items[x].attack);
						defense_total += parseInt(Items[x].equipped_defense*Items[x].defense);
					}
					if (!own) { //list top 501 items, including not owned
						// if ((Items[x].tradeable == 1) && (i_improvement[0] > 0)) {
							//analyze[analyze.length] = '<div name="'+Locations[Items[x].location+''].name+'">['+itemtype+'] <span class="good">'+i_improvement[0]+'x</span> '+Items[x].name+' for '+sortby+' increase: <span class="good">'+commas(i_improvement[1])+'</span>. Source: '+Locations[Items[x].location+''].name+' or gift.'+'</div>';
							// if (analyze_dupecheck.search(Items[x].name) < 0) {
								// analyze[analyze.length] = '<div name="Gifting">['+itemtype+'] <span class="good">'+i_improvement[0]+'x</span> '+Items[x].name+' for '+sortby+' increase: <span class="good">'+commas(i_improvement[1])+'</span>. Source: '+Locations[Items[x].location+''].name+' or gift.'+'</div>';
								// analyze_dupecheck += Items[x].name+'|';
							// }
						// }
						// if (Items[x].purchasable && (i_improvement[0] > 0)) {
							// if (analyze_dupecheck.search(Items[x].name) < 0) {
								// analyze[analyze.length] = '<div name="'+Locations[Items[x].location+''].name+'">['+itemtype+'] <span class="good">'+i_improvement[0]+'x</span> '+Items[x].name+' ('+Items[x].formated_price.substr(0,2)+''+commas((i_improvement[0])*Items[x].cash_price)+') for '+sortby+' increase: <span class="good">'+commas(i_improvement[1])+'</span>. Source: Buy in '+Locations[Items[x].location+''].name+'</div>';
								// analyze_dupecheck += Items[x].name+'|';
							// }
						// }
						// if ((Items[x].rp_price > 0) && (i_improvement[0] > 0)) {
							// if (analyze_dupecheck.search(Items[x].name) < 0) {
								// analyze[analyze.length] = '<div name="'+Locations[Items[x].location+''].name+'">['+itemtype+'] <span class="good">'+i_improvement[0]+'x</span> '+Items[x].name+' (RP: '+commas(i_improvement[0]*Items[x].rp_price)+') for '+sortby+' increase: <span class="good">'+commas(i_improvement[1])+'</span>. Source: Buy in '+Locations[Items[x].location+''].name+'</div>';
								// analyze_dupecheck += Items[x].name+'|';
							// }
						// }
					
					
						if (using > 0 && Items[x].active) { //item we use
							body += '<tr style="background-color:'+(zebra%2?'#000000':'#202020')+'"><td>'+Qualities[Items[x].quality+''].image+'</td><td>'+Items[x].name+'</td><td>'+Items[x].attack+'</td><td>'+Items[x].defense+'</td><td>'+((count+using)>mafiasize?mafiasize-count:using)+'</td><td>'+Items[x].quantity+'</td><td>'+locationtext+'</td><td>'+wishlist+'</td></tr>\n';
							count += parseInt(using);
							zebra++;
							//console.log(analyze_dupecheck);
							// if ((Items[x].tradeable == 1) && (mafiasize-count > 0)) {
								// analyze[analyze.length] = '['+itemtype+'] <span class="good">'+(mafiasize-count)+'x</span> '+Items[x].name+' for '+sortby+' increase: <span class="good">'+commas(((mafiasize-count)*Items[x][sortby]))+'</span>. Source: '+Locations[Items[x].location+''].name+' or gift.';
							// }
							// if (Items[x].purchasable && (mafiasize-count > 0)) {
								// analyze[analyze.length] = '['+itemtype+'] <span class="good">'+(mafiasize-count)+'x</span> '+Items[x].name+' ('+Items[x].formated_price.substr(0,2)+''+commas((mafiasize-count)*Items[x].cash_price)+') for '+sortby+' increase: <span class="good">'+commas(((mafiasize-count)*Items[x][sortby]))+'</span>. Source: Buy in '+Locations[Items[x].location+''].name;
							// }
							// if ((Items[x].rp_price > 0) && (mafiasize-count > 0)) {
								// analyze[analyze.length] = '['+itemtype+'] <span class="good">'+(mafiasize-count)+'x</span> '+Items[x].name+' (RP: '+commas((mafiasize-count)*Items[x].rp_price)+') for '+sortby+' increase: <span class="good">'+commas(((mafiasize-count)*Items[x][sortby]))+'</span>. Source: Buy in '+Locations[Items[x].location+''].name;
							// }
						}
						else if (Items[x].quantity > 0 && Items[x].active) { //have but not used
							body += '<tr style="background-color:'+(zebra%2?'#000000':'#202020')+'"><td>'+Qualities[Items[x].quality+''].image+'</td><td>'+Items[x].name+'</td><td>'+Items[x].attack+'</td><td>'+Items[x].defense+'</td><td>'+((count+using)>mafiasize?mafiasize-count:using)+'</td><td>'+Items[x].quantity+'</td><td>'+locationtext+'</td><td>'+wishlist+'</td></tr>\n';
							zebra++;
						}
						else { //item we do not have
							body += '<tr style="background-color:'+(zebra%2?'#000000':'#202020')+'"><td>'+Qualities[Items[x].quality+''].image+'</td><td><span class="bad">'+Items[x].name+'</span></td><td>'+Items[x].attack+'</td><td>'+Items[x].defense+'</td><td>'+((count+using)>mafiasize?mafiasize-count:using)+'</td><td>'+Items[x].quantity+'</td><td>'+locationtext+'</td><td>'+wishlist+'</td></tr>\n';						
							zebra++;
						}
					}
					// else { //list all items
						// body += '<tr style="background-color:'+(zebra%2?'#000000':'#202020 ')+'"><td><span class="'+(using == 0?'bad')+'">'+Items[x].name+'</span></td><td>'+Items[x].attack+'</td><td>'+Items[x].defense+'</td><td>'+((count+using)>mafiasize?mafiasize-count:using)+'/'+Items[x].quantity+'</td><td>'+locationtext+'</td><td>'+wishlist+'</td></tr>\n';						
					// }
				}
				else { //handle all non Weapon, Armor, Vehicle or Animal items
					analyze = [];
					body += '<tr style="background-color:'+(zebra%2?'#000000':'#202020')+'"><td></td><td><span class="'+(Items[x].quantity <= 0?'bad':'')+'">'+Items[x].name+'</span></td><td colspan="3">'+Items[x].specialAbility+'</td><td>'+Items[x].quantity+'</td><td>'+location+'</td><td>'+wishlist+'</td></tr>\n';
					zebra++;
				}
			}
			if (/NotUsing/.test(type)) {
				var regex = new RegExp(itemtype);
				if (limit == 0){ break; }
				analyze = [];
				if (Items[x].cash_price > 0) {
					wishlist = 'Sell for '+Items[x].formated_price+' each';
				}
				//if ((regex.test(type)) && (max_using < Items[x].quantity) && (Items[x].quantity > 0) && ((Items[x].tradeable == 1) || (Items[x].cash_price > 0))) { //not used giftable items
				if ((regex.test(type)) && (max_using < Items[x].quantity) && (Items[x].quantity > 0) && ((Items[x].tradeable == 1) || (Items[x].cash_price > 0))) { //not used giftable items
					//body += '<tr style="background-color:'+(zebra%2?'#000000':'#202020')+'"><td>'+Items[x].name+'</td><td>'+Items[x].attack+'</td><td>'+Items[x].defense+'</td><td>'+parseInt(Items[x].quantity-max_using)+'</td><td>'+Items[x].quantity+'</td><td></td><td>'+wishlist+'</td></tr>\n';
					body += '<tr style="background-color:'+(zebra%2?'#000000':'#202020')+'"><td>'+Qualities[Items[x].quality+''].image+'</td><td>'+Items[x].name+'</td><td>'+Items[x].attack+'</td><td>'+Items[x].defense+'</td><td>'+parseInt(Items[x].quantity-max_using)+'</td><td></td><td>'+wishlist+'</td></tr>\n';
					zebra++;
					limit--;
				}			
			}
			//if (checkCountcheckCount) { break; }
			if ((count >= mafiasize) || (count >= 501)) {
				break;
			}
		}
		body += '</table>';
		if (parseInt($('#attack_total').html()) < attack_total) {
			$('#attack_total').html(attack_total);
		}
		if (parseInt($('#defense_total').html()) < defense_total) {
			$('#defense_total').html(defense_total);
		}
		var analyze_output = '';
		for (i=0;i<analyze.length;i++) {
			//analyze_output += analyze[i]+'<br />';
			analyze_output += analyze[i];
		}
		$('#analyze_output').html(analyze_output);
		
		//outputObject(QualityHave,'debug_output');
	}

	function qualityStats(object,elementid) {
		var base = 620; //width for the entire bar
		var output = 
		'<img src="http://mwfb.static.zgncdn.com/mwfb/graphics/quality/Inventory-ultimate-icon.png" alt="Item Quality: Ultimate" title="Item Quality: Ultimate" /> Ultimate: '+object.Ultimate+' <span class="more_in">('+parseFloat(object.Ultimate*100/object.total).toFixed(0)+'%)</span>'+
		' <img src="http://mwfb.static.zgncdn.com/mwfb/graphics/quality/Inventory-superior-icon.png" alt="Item Quality: Superior" title="Item Quality: Superior" /> Superior: '+object.Superior+' <span class="more_in">('+parseFloat(object.Superior*100/object.total).toFixed(0)+'%)</span>'+
		' <img src="http://mwfb.static.zgncdn.com/mwfb/graphics/quality/Inventory-rare-icon.png" alt="Item Quality: Rare" title="Item Quality: Rare" /> Rare: '+object.Rare+' <span class="more_in">('+parseFloat(object.Rare*100/object.total).toFixed(0)+'%)</span>'+
		' <img src="http://mwfb.static.zgncdn.com/mwfb/graphics/quality/Inventory-uncommon-icon.png" alt="Item Quality: Uncommon" title="Item Quality: Uncommon" /> Uncommon: '+object.Uncommon+' <span class="more_in">('+parseFloat(object.Uncommon*100/object.total).toFixed(0)+'%)</span>'+
		' <img src="http://mwfb.static.zgncdn.com/mwfb/graphics/quality/Inventory-common-icon.png" alt="Item Quality: Common" title="Item Quality: Common" /> Common: '+object.Common+' <span class="more_in">('+parseFloat(object.Common*100/object.total).toFixed(0)+'%)</span>'+
		'  Total: '+object.total;
		
		var common = '<div style="float: left; width: '+parseFloat(base*(object.Common/object.total).toFixed(2))+'px; height: 10px; background: url(\'http://mwfb.static.zgncdn.com/mwfb/graphics/inventory/summary/ProgressBar/progress-bar-common.png\') repeat scroll 0% 0% transparent;" title="White represents Common items"></div>';
		var uncommon = '<div style="float: left; width: '+parseFloat(base*(object.Uncommon/object.total).toFixed(2))+'px; height: 10px; background: url(\'http://mwfb.static.zgncdn.com/mwfb/graphics/inventory/summary/ProgressBar/progress-bar-uncommon.png\') repeat scroll 0% 0% transparent;" title="Green represents Uncommon items"></div>';
		var rare = '<div style="float: left; width: '+parseFloat(base*(object.Rare/object.total).toFixed(2))+'px; height: 10px; background: url(\'http://mwfb.static.zgncdn.com/mwfb/graphics/inventory/summary/ProgressBar/progress-bar-rare.png\') repeat scroll 0% 0% transparent;" title="Blue represents Rare items"></div>';
		var superior = '<div style="float: left; width: '+parseFloat(base*(object.Superior/object.total).toFixed(2))+'px; height: 10px; background: url(\'http://mwfb.static.zgncdn.com/mwfb/graphics/inventory/summary/ProgressBar/progress-bar-superior.png\') repeat scroll 0% 0% transparent;" title="Orange represents Superior items"></div>';
		var ultimate = '<div style="float: left; width: '+parseFloat(base*(object.Ultimate/object.total).toFixed(2))+'px; height: 10px; background: url(\'http://mwfb.static.zgncdn.com/mwfb/graphics/inventory/summary/ProgressBar/progress-bar-ultimate.png\') repeat scroll 0% 0% transparent;" title="Yellow represents Ultimate items"></div>';
		
		$('#'+elementid+'_bar').html(ultimate+superior+rare+uncommon+common);
		$('#'+elementid).html(output);
	}	
	function outputObject(object,elementid) {
		var output = '';
		for (x in object) {
			output += x+' '+object[x]+' ';
		}
		$('#'+elementid).html(output);
	}
	
	function debugOutputObject(object,elementid) {
		//used for debug to output a object to a specified elemntid
		var debug_output = '';
		var count = 0;
		for (x in object) {
			debug_output += x+' '+object[x]+'<br />';
			if (typeof object[x] == 'number') {
				count += object[x];
			}
			if (typeof object[x] == 'object') {
				for (y in object[x]) {
					debug_output += y+' '+object[x][y]+'<br />';
					if (typeof object[x] == 'number') {
						count += object[x];
					}
				}
			}
		}
		$('#'+elementid).html(debug_output);
	}
	
	function readNewInventory() {
		function unix_timestamp() {
			return parseInt(new Date().getTime().toString().substring(0, 10))
		}
		var userid = /sf_xw_user_id=([a-z]\|[0-9]+)/.exec(document.body.innerHTML)[1];
		var cb = userid+unix_timestamp();
		var params = {
			'ajax': 1, 
			'liteload': 1, 
			'sf_xw_user_id': userid,
			'sf_xw_sig': local_xw_sig,
			'cb': cb,
			'xw_client_id': 8,
			'skip_req_frame': 1
		};
		$.ajax({
			type: "POST",
			url: 'http://facebook.mafiawars.com/mwfb/remote/html_server.php?xw_controller=inventory&xw_action=view&xw_city=&from_controller=inventory',
			data: params,
			success: function (response) {
				if (debugoutput) { //normal case
					try {
						$('#spocktext').html('Page is now loaded, parsing the content...');
						var ZyngaItems = jQuery.parseJSON(/var Items = \{\s+data: (\{.*?\})\};/.exec(response)[1]);
						for (x in ZyngaItems) {
							ZyngaItems[x].combined = parseInt(ZyngaItems[x].attack+ZyngaItems[x].defense);
							Items[Items.length] = ZyngaItems[x];
						}
						
						if (typeof Item.Qualities == 'object') {
							Qualities = Item.Qualities;
							//console.log('Using Zynga data for Qualities');
						}
						else {
							Qualities = {
								"1":{"name":"Common","loc_name":"Common","image":"<img src=\"http:\/\/mwfb.static.zgncdn.com\/mwfb\/graphics\/quality\/Inventory-common-icon.png\" alt=\"Item Quality: Common\" title=\"Item Quality: Common\" \/>","raw_img":"http:\/\/mwfb.static.zgncdn.com\/mwfb\/graphics\/quality\/Inventory-common-icon.png"},
								"2":{"name":"Uncommon","loc_name":"Uncommon","image":"<img src=\"http:\/\/mwfb.static.zgncdn.com\/mwfb\/graphics\/quality\/Inventory-uncommon-icon.png\" alt=\"Item Quality: Uncommon\" title=\"Item Quality: Uncommon\" \/>","raw_img":"http:\/\/mwfb.static.zgncdn.com\/mwfb\/graphics\/quality\/Inventory-uncommon-icon.png"},
								"3":{"name":"Rare","loc_name":"Rare","image":"<img src=\"http:\/\/mwfb.static.zgncdn.com\/mwfb\/graphics\/quality\/Inventory-rare-icon.png\" alt=\"Item Quality: Rare\" title=\"Item Quality: Rare\" \/>","raw_img":"http:\/\/mwfb.static.zgncdn.com\/mwfb\/graphics\/quality\/Inventory-rare-icon.png"},
								"4":{"name":"Superior","loc_name":"Superior","image":"<img src=\"http:\/\/mwfb.static.zgncdn.com\/mwfb\/graphics\/quality\/Inventory-superior-icon.png\" alt=\"Item Quality: Superior\" title=\"Item Quality: Superior\" \/>","raw_img":"http:\/\/mwfb.static.zgncdn.com\/mwfb\/graphics\/quality\/Inventory-superior-icon.png"},
								"5":{"name":"Ultimate","loc_name":"Ultimate","image":"<img src=\"http:\/\/mwfb.static.zgncdn.com\/mwfb\/graphics\/quality\/Inventory-ultimate-icon.png\" alt=\"Item Quality: Ultimate\" title=\"Item Quality: Ultimate\" \/>","raw_img":"http:\/\/mwfb.static.zgncdn.com\/mwfb\/graphics\/quality\/Inventory-ultimate-icon.png"}
							};
						}
						if (typeof Item.Locations == 'object') {
							Locations = Item.Locations;
							//console.log('Using Zynga data for Locations');
						}
						else {
							Locations = {
								"1":{"name":"New York","loc_name":"New York","description":"","link":"remote\/html_server.php?xw_controller=travel&xw_action=travel&xw_city=7&tmp=&cb=&xw_person=&mwcom=1&destination=1&from=Job"},
								"2":{"name":"Cuba","loc_name":"Cuba","description":"","link":"remote\/html_server.php?xw_controller=travel&xw_action=travel&xw_city=7&tmp=&cb=&xw_person=&mwcom=1&destination=2&from=Job"},
								"3":{"name":"Moscow","loc_name":"Moscow","description":"","link":"remote\/html_server.php?xw_controller=travel&xw_action=travel&xw_city=7&tmp=&cb=&xw_person=&mwcom=1&destination=3&from=Job"},
								"4":{"name":"Bangkok","loc_name":"Bangkok","description":"","link":"remote\/html_server.php?xw_controller=travel&xw_action=travel&xw_city=7&tmp=&cb=&xw_person=&mwcom=1&destination=4&from=Job"},
								"5":{"name":"Las Vegas","loc_name":"Las Vegas","description":"","link":"remote\/html_server.php?xw_controller=travel&xw_action=travel&xw_city=7&tmp=&cb=&xw_person=&mwcom=1&destination=5&from=Job"},
								"6":{"name":"Italy","loc_name":"Italy","description":"","link":"remote\/html_server.php?xw_controller=travel&xw_action=travel&xw_city=7&tmp=&cb=&xw_person=&mwcom=1&destination=6&from=Job"},
								"7":{"name":"Challenge Mission","loc_name":"Challenge Mission","description":"","link":""},
								"8":{"name":"Gifting","loc_name":"Gifting","description":"","link":""},
								"9":{"name":"Marketplace","loc_name":"Marketplace","description":"","link":"remote\/html_server.php?xw_controller=marketplace&xw_action=view&xw_city=7&tmp=&cb=&xw_person=&mwcom=1"},
								"10":{"name":"Special Event","loc_name":"Special Event","description":"","link":""},
								"11":{"name":"Fighting","loc_name":"Fighting","description":"","link":"remote\/html_server.php?xw_controller=fight&xw_action=view&xw_city=7&tmp=&cb=&xw_person=&mwcom=1"},
								"12":{"name":"Robbing","loc_name":"Robbing","description":"","link":"remote\/html_server.php?xw_controller=robbing&xw_action=view&xw_city=7&tmp=&cb=&xw_person=&mwcom=1"},
								"13":{"name":"Operations","loc_name":"Operations","description":"","link":""},
								"14":{"name":"Property","loc_name":"Property","description":"","link":""},
								"15":{"name":"Declare War","loc_name":"Declare War","description":"","link":"remote\/html_server.php?xw_controller=war&xw_action=view&xw_city=7&tmp=&cb=&xw_person=&mwcom=1"},
								"16":{"name":"Mission","loc_name":"Mission","description":"","link":"remote\/html_server.php?xw_controller=index&xw_action=view&xw_city=7&tmp=&cb=&xw_person=&mwcom=1"},
								"17":{"name":"Zpoints\/RewardVille","loc_name":"Zpoints\/RewardVille","description":"","link":"remote\/html_server.php?xw_controller=index&xw_action=view&xw_city=7&tmp=&cb=&xw_person=&mwcom=1"},
								"18":{"name":"Brazil","loc_name":"Brazil","description":"Some shitty description","link":"remote\/html_server.php?xw_controller=travel&xw_action=travel&xw_city=7&tmp=&cb=&xw_person=&mwcom=1&destination=7&from=Job"}
							};
						}
						if (typeof Item.Subtypes == 'object') {
							Subtypes = Item.Subtypes;
							//console.log('Using Zynga data for Subtypes');
						}
						else {
							Subtypes = {"1":{"name":"Handgun","loc_name":"Handgun"},"2":{"name":"Explosive","loc_name":"Explosive"},"3":{"name":"Blade","loc_name":"Blade"},"4":{"name":"Hi-tech","loc_name":"Hi-tech"},"5":{"name":"Automatic","loc_name":"Automatic"},"6":{"name":"Antique","loc_name":"Antique"},"7":{"name":"Clothing","loc_name":"Clothing"},"8":{"name":"Ballistic","loc_name":"Ballistic"},"9":{"name":"Helicopter","loc_name":"Helicopter"},"10":{"name":"Shotgun","loc_name":"Shotgun"},"11":{"name":"Car","loc_name":"Car"},"12":{"name":"Truck","loc_name":"Truck"},"13":{"name":"Motorcycle","loc_name":"Motorcycle"},"14":{"name":"Plane","loc_name":"Plane"},"15":{"name":"Aquatic","loc_name":"Aquatic"},"16":{"name":"Bird","loc_name":"Bird"},"17":{"name":"Reptile","loc_name":"Reptile"},"18":{"name":"Bug","loc_name":"Bug"},"19":{"name":"Canine","loc_name":"Canine"},"20":{"name":"Feline","loc_name":"Feline"},"21":{"name":"Rifle","loc_name":"Rifle"},"22":{"name":"Melee","loc_name":"Melee"},"23":{"name":"Person","loc_name":"Person"},"24":{"name":"Head","loc_name":"Head"},"25":{"name":"Body","loc_name":"Body"},"26":{"name":"Arms","loc_name":"Arms"},"27":{"name":"Legs","loc_name":"Legs"},"28":{"name":"Watercraft","loc_name":"Watercraft"},"29":{"name":"Machine Gun","loc_name":"Machine Gun"},"30":{"name":"Insect","loc_name":"Insect"},"31":{"name":"Armored","loc_name":"Armored"}};
						}
						if (typeof Item.Types == 'object') {
							ItemTypes = Item.Types;
							//console.log('Using Zynga data for ItemTypes');
						}
						else {
							ItemTypes = {"8":"Animals","1":"Weapons","2":"Armor","3":"Vehicles","4":"Extra","5":"Boss Loot","6":"Job Mastery","9":"Treasure Chest"};
						}
						//Qualities = jQuery.parseJSON(/var Qualities = \{\s+data: (\{.*?\})\};/.exec(response)[1]);
						//Locations = jQuery.parseJSON(/var Locations = \{\s+data: (\{.*?\})\};/.exec(response)[1]);
						//Subtypes = jQuery.parseJSON(/var Subtypes = \{\s+data: (\{.*?\})\};/.exec(response)[1]);
						//ItemTypes = jQuery.parseJSON(/var ItemTypes = \{\s+data: (\{.*?\})\};/.exec(response)[1]);
						//cityCashImg = jQuery.parseJSON(/cityCashImg: (.*?}),/.exec(response)[1]);
						mafiasize = /user_group_size.*?(\d+)/.exec(response)[1];
						$('#spocktext').html('Inventory is now loaded, use links to change sorting.<br />'+
						'What more stats? <a href="http://www.facebook.com/topic.php?uid=92178514356&topic=24399">Make suggestion</a> - Found a bug? <a href="http://www.facebook.com/topic.php?uid=92178514356&topic=25009">Alert Spockholm</a><br />'+
						'The [Send Gift] link causes a heavy page reload and the gifting page is shown at the bottom of the page.');
						sortByAttack();
					}
					catch (loaderror) {
						$('#spocktext').html('We encountered a problem, don\'t panic! Reload the game and restart your browser.<br />Then read <a href="http://www.spockholm.com/mafia/help.php#bugreporting">the instructions</a> how to write a bug report. Submit the detailed report <a href="<a href="http://www.facebook.com/topic.php?uid=92178514356&topic=25009">here</a>.<br /><span class="bad">'+loaderror+'</span>');
					}
				}
				else {
					$('#spocktext').html('Page is now loaded, parsing the content...');
					var ZyngaItems = jQuery.parseJSON(/var Items = \{\s+data: (\{.*?\})\};/.exec(response)[1]);
					for (x in ZyngaItems) {
						ZyngaItems[x].combined = parseInt(ZyngaItems[x].attack+ZyngaItems[x].defense);
						Items[Items.length] = ZyngaItems[x];
						//console.log(Items[Items.length].combined);
					}
					Qualities = jQuery.parseJSON(/var Qualities = \{\s+data: (\{.*?\})\};/.exec(response)[1]);
					Locations = jQuery.parseJSON(/var Locations = \{\s+data: (\{.*?\})\};/.exec(response)[1]);
					//btypes = eval("("+/var Subtypes = \{\s+data: (\{.*?\})\};/.exec(response)[1]+")");
					Subtypes = jQuery.parseJSON(/var Subtypes = \{\s+data: (\{.*?\})\};/.exec(response)[1]);
					ItemTypes = jQuery.parseJSON(/var ItemTypes = \{\s+data: (\{.*?\})\};/.exec(response)[1]);
					mafiasize = /user_group_size.*?(\d+)/.exec(response)[1];
					$('#spocktext').html('Inventory is now loaded, use links to change sorting.<br />'+
					'What more stats? <a href="http://www.facebook.com/topic.php?uid=92178514356&topic=24399">Make suggestion</a> - Having trouble? <a href="http://www.spockholm.com/mafia/help.php#bugreporting">Get help</a> - Found a bug? <a href="http://www.facebook.com/topic.php?uid=92178514356&topic=25009">Alert Spockholm</a> after reading the <a href="http://www.spockholm.com/mafia/help.php#bugreporting">bug report instructions</a>.<br />'+
					'The [Send Gift] link causes a heavy page reload and the gifting page is shown at the bottom of the page.');
					sortByAttack();
				}
			}
		});
	}
	readNewInventory();

	
	head += '<div id="spockloot" style="border: 1px solid #ccc; padding: 3px;">\n';
	head += '<h2>'+version+'</h2>';
	head += '<p>Mafia: <input type="text" id="mafiasize" value="'+mafiasize+'" size="9"> &nbsp; Attack: <span id="attack_total">0</span> Defense: <span id="defense_total">0</span></p>\n';
	head += '<p>Top items by: [<a href="#" id="attack">Attack</a> (<a href="#" id="attack_all">all</a>)] [<a href="#" id="defense">Defense</a> (<a href="#" id="defense_all">all</a>)] [<a href="#" id="combined">Combined</a>]&nbsp; &nbsp; [<a href="http://www.spockholm.com/mafia/donate.php?ItemAnalyzer" target="_blank">Donate Coffee/Beer</a>][<a href="#" onclick="javascript:$(\'#spockloot\').remove();return false;">Close <img src="'+stopimg+'" alt="Close" title="Close" width="16" height="12"></a>]</p>\n';
	head += '<p>Not Using (By Attack): [<a href="#" id="notusing-weapons">Weapons</a>] [<a href="#" id="notusing-armor">Armor</a>] [<a href="#" id="notusing-vehicles">Vehicles</a>] [<a href="#" id="notusing-animals">Animals</a>] [<a href="#" id="notusing">All</a>] [<a href="#" id="notusing5">Top-5</a>]</p>';
	head += '<p>Not Using (By Defense): [<a href="#" id="notusing-weapons-def">Weapons</a>] [<a href="#" id="notusing-armor-def">Armor</a>] [<a href="#" id="notusing-vehicles-def">Vehicles</a>] [<a href="#" id="notusing-animals-def">Animals</a>] [<a href="#" id="notusing-def">All</a>] [<a href="#" id="notusing-def5">Top-5</a>]</p>';
	head += '<p>Extra items: [<a href="#" id="boss">Boss Loot</a>] [<a href="#" id="mastery">Job Mastery</a>] [<a href="#" id="extra">Extra Items</a>]</p>\n';
	head += '<p>Popup all owned, sorted by: [<a href="#" id="popup-attack" name="popup">Attack</a>] [<a href="#" id="popup-defense" name="popup">Defense</a>]</p>\n';
	head += '<p class="more_in" id="spocktext">Bookmarklet is now loading your inventory page, it can take a few seconds...<img src="http://facebook.mafiawars.com/mwfb/graphics/mobileWeb/320/loader.gif" align="middle" /></p>\n';
	head += '<p id="debug_output"></p>'
	head += '<p>[<a href="#" id="suggestions">Hiding</a> Item Suggestions][<a href="#" class="display_toggle" name="Marketplace">Showing</a> Marketplace Items][<a href="#" class="display_toggle" name="Gifting">Showing</a> Gifting Items]</p>'
	head += '<p id="analyze_output" style="display:none;"></p>';
	body += '<div id="showloot"></div>';
	tail += '</div>\n';
	$('#spockloot').remove();
	$('#analyze_output').hide();
	$('#content_row').eq(0).before(head+body+tail);

	document.getElementById('suggestions').onclick=function() {
		if ($(this).html() == 'Hiding') {
			$('#analyze_output').slideDown();
			//$('#analyze_output').show();
			$(this).html('Showing');
		}
		else {
			$('#analyze_output').slideUp();
			//$('#analyze_output').hide();
			$(this).html('Hiding');
		}
		//onclick="javascript:$(\'#analyze_output\').hide();return false;"
	}
	for (i=0; i<document.getElementsByClassName('display_toggle').length;i++) {
		document.getElementsByClassName('display_toggle')[i].onclick = display_toggle;
	}
	function display_toggle() {
		if ($(this).html() == 'Hiding') {
			//$("div[name="+this.name+"]").show();
			$("div[name="+this.name+"]").slideDown();
			$(this).html('Showing');
		}
		else {
			//$("div[name="+this.name+"]").hide();
			$("div[name="+this.name+"]").slideUp();
			$(this).html('Hiding');
		}
	}
	//This part needs to be re-witten into something more generic
	//one big onclick function that determines the proper usage by this.id or this.name
	document.getElementById('attack').onclick=sortByAttack;
	function sortByAttack() {
		body = '';
		analyze = [];
		analyze_dupecheck = '';
		QualityHave = [];
		attack_total = 0, defense_total = 0;
		mafiasize = parseInt($("#mafiasize").val());
		//         sorting  header  own  type
		writeTable('attack','Weapons',true,'Weapons');
		writeTable('attack','Armor',true,'Armor');
		writeTable('attack','Vehicles',true,'Vehicles');
		writeTable('attack','Animals',true,'Animals');
		$('#showloot').html(body);
		qualityStats(QualityHave.Weapons,'Weapons');
		qualityStats(QualityHave.Armor,'Armor');
		qualityStats(QualityHave.Vehicles,'Vehicles');
		qualityStats(QualityHave.Animals,'Animals');
		return false;
	};
	document.getElementById('attack_all').onclick=function() {
		body = '';
		analyze = [];
		analyze_dupecheck = '';
		attack_total = 0, defense_total = 0;
		mafiasize = parseInt($("#mafiasize").val());
		writeTable('attack','Weapons',false,'Weapons');
		writeTable('attack','Armor',false,'Armor');
		writeTable('attack','Vehicles',false,'Vehicles');
		writeTable('attack','Animals',false,'Animals');
		$('#showloot').html(body);
		return false;
	};
	
	document.getElementById('notusing').onclick=function() {
		body = '';
		attack_total = 0, defense_total = 0;
		writeTable('attack','Weapons',true,'NotUsing-Weapons');
		writeTable('attack','Armor',true,'NotUsing-Armor');
		writeTable('attack','Vehicles',true,'NotUsing-Vehicles');
		writeTable('attack','Animals',true,'NotUsing-Animals');
		$('#showloot').html(body);
		return false;
	};
	document.getElementById('notusing5').onclick=function() {
		body = '';
		attack_total = 0, defense_total = 0;
		writeTable('attack','Weapons',true,'NotUsing-Weapons',5);
		writeTable('attack','Armor',true,'NotUsing-Armor',5);
		writeTable('attack','Vehicles',true,'NotUsing-Vehicles',5);
		writeTable('attack','Animals',true,'NotUsing-Animals',5);
		$('#showloot').html(body);
		return false;
	};
	document.getElementById('notusing-weapons').onclick=function() {
		body = '';
		attack_total = 0, defense_total = 0;
		writeTable('attack','Weapons',true,'NotUsing-Weapons');
		$('#showloot').html(body);
		return false;
	};
	document.getElementById('notusing-armor').onclick=function() {
		body = '';
		attack_total = 0, defense_total = 0;
		writeTable('attack','Armor',true,'NotUsing-Armor');
		$('#showloot').html(body);
		return false;
	};
	document.getElementById('notusing-vehicles').onclick=function() {
		body = '';
		attack_total = 0, defense_total = 0;
		writeTable('attack','Vehicles',true,'NotUsing-Vehicles');
		$('#showloot').html(body);
		return false;
	};
	document.getElementById('notusing-animals').onclick=function() {
		body = '';
		attack_total = 0, defense_total = 0;
		writeTable('attack','Animals',true,'NotUsing-Animals');
		$('#showloot').html(body);
		return false;
	};
	document.getElementById('notusing-def').onclick=function() {
		body = '';
		attack_total = 0, defense_total = 0;
		writeTable('defense','Weapons',true,'NotUsing-Weapons');
		writeTable('defense','Armor',true,'NotUsing-Armor');
		writeTable('defense','Vehicles',true,'NotUsing-Vehicles');
		writeTable('defense','Animals',true,'NotUsing-Animals');
		$('#showloot').html(body);
		return false;
	};
	document.getElementById('notusing-def5').onclick=function() {
		body = '';
		attack_total = 0, defense_total = 0;
		writeTable('defense','Weapons',true,'NotUsing-Weapons',5);
		writeTable('defense','Armor',true,'NotUsing-Armor',5);
		writeTable('defense','Vehicles',true,'NotUsing-Vehicles',5);
		writeTable('defense','Animals',true,'NotUsing-Animals',5);
		$('#showloot').html(body);
		return false;
	};
	document.getElementById('notusing-weapons-def').onclick=function() {
		body = '';
		attack_total = 0, defense_total = 0;
		writeTable('defense','Weapons',true,'NotUsing-Weapons');
		$('#showloot').html(body);
		return false;
	};
	document.getElementById('notusing-armor-def').onclick=function() {
		body = '';
		attack_total = 0, defense_total = 0;
		writeTable('defense','Armor',true,'NotUsing-Armor');
		$('#showloot').html(body);
		return false;
	};
	document.getElementById('notusing-vehicles-def').onclick=function() {
		body = '';
		attack_total = 0, defense_total = 0;
		writeTable('defense','Vehicles',true,'NotUsing-Vehicles');
		$('#showloot').html(body);
		return false;
	};
	document.getElementById('notusing-animals-def').onclick=function() {
		body = '';
		attack_total = 0, defense_total = 0;
		writeTable('defense','Animals',true,'NotUsing-Animals');
		$('#showloot').html(body);
		return false;
	};
	
	document.getElementById('defense').onclick=function() {
		body = '';
		analyze = [];
		analyze_dupecheck = '';
		QualityHave = [];
		attack_total = 0, defense_total = 0;
		mafia = parseInt($("#mafiasize").val());
		writeTable('defense','Weapons',true,'Weapons');
		writeTable('defense','Armor',true,'Armor');
		writeTable('defense','Vehicles',true,'Vehicles');
		writeTable('defense','Animals',true,'Animals');
		$('#showloot').html(body);
		qualityStats(QualityHave.Weapons,'Weapons');
		qualityStats(QualityHave.Armor,'Armor');
		qualityStats(QualityHave.Vehicles,'Vehicles');
		qualityStats(QualityHave.Animals,'Animals');
		return false;
	};
	document.getElementById('defense_all').onclick=function() {
		body = '';
		analyze = [];
		analyze_dupecheck = '';
		attack_total = 0, defense_total = 0;
		mafiasize = parseInt($("#mafiasize").val());
		writeTable('defense','Weapons',false,'Weapons');
		writeTable('defense','Armor',false,'Armor');
		writeTable('defense','Vehicles',false,'Vehicles');
		writeTable('defense','Animals',false,'Animals');
		$('#showloot').html(body);
		return false;
	};
	
	document.getElementById('combined').onclick=function() {
		body = '';
		analyze = [];
		analyze_dupecheck = '';
		QualityHave = [];
		attack_total = 0, defense_total = 0;
		mafia = parseInt($("#mafiasize").val());
		writeTable('combined','Weapons',true,'Weapons');
		writeTable('combined','Armor',true,'Armor');
		writeTable('combined','Vehicles',true,'Vehicles');
		writeTable('combined','Animals',true,'Animals');
		$('#showloot').html(body);
		qualityStats(QualityHave.Weapons,'Weapons');
		qualityStats(QualityHave.Armor,'Armor');
		qualityStats(QualityHave.Vehicles,'Vehicles');
		qualityStats(QualityHave.Animals,'Animals');
		return false;
	};

	document.getElementById('boss').onclick=function() {
		body = '';
		writeTable('location','Boss Items',true,'Boss Loot');
		$('#showloot').html(body);
		return false;
	};
	document.getElementById('mastery').onclick=function() {
		body = '';
		writeTable('location','Job Mastery',true,'Job Mastery');
		$('#showloot').html(body);
		return false;
	};
	document.getElementById('extra').onclick=function() {
		body = '';
		writeTable('location','Extra',true,'Extra');
		$('#showloot').html(body);
		return false;
	};
	
	// document.getElementById('special').onclick=function() {
		// body = '';
		// writeTable('location','Super Special',true,'Super Special');
		// $('#showloot').html(body);
		// return false;
	// };

	$('a[name="popup"]').click(function() {
		var sort = /popup-(.*)/.exec(this.id)[1];
		popup(sort);
	});
	
	function popup(sortby) {
		function customSort(property) {
			return function (b, a) {
				return parseInt(a[property]) - parseInt(b[property]);
			};
		}
		if (typeof sortby == 'string') { //only sort if we get a string
			Items.sort(customSort(sortby));
		}
		var popup = window.open('','name','height=500,width=500,scrollbars=yes');
		
		popup.document.write('<pre><table>');
		popup.document.write('<th>ID</th><th>Name</th><th>Attack</th><th>Defense</th><th>Quantity</th><th>Type</th><th>SubTypes</th><th>Location</th>');
		for (x in Items) {
			if (Items[x].quantity > 0) {
				var locationtext = '';
				if (typeof Items[x].location == 'number') {
					locationtext = Locations[Items[x].location+''].name;
				}
				var itemtype = 'Unknown';
				if (typeof Items[x].type == 'number') {
					itemtype = ItemTypes[Items[x].type+''];
				}
				var subtypes = '';
				for (y in Items[x].subtypes) {
					subtypes += Subtypes[Items[x].subtypes[y]+''].name;
				}
				popup.document.write('<tr><td>'+
				Items[x].id+'</td><td>'+
				Items[x].name+'</td><td>'+
				Items[x].attack+'</td><td>'+
				Items[x].defense+'</td><td>'+
				Items[x].quantity+'</td><td>'+
				itemtype+'</td><td>'+
				subtypes+'</td><td>'+
				locationtext+'</td></tr>');
			}
		}
		popup.document.write('</table></pre>');
		popup.document.close();
	}
	
	//add analytics
	function loadContent(file){
		var head = document.getElementsByTagName('head').item(0);
		var scriptTag = document.getElementById('loadScript');
		if(scriptTag) head.removeChild(scriptTag);
			script = document.createElement('script');
			script.src = file;
			script.type = 'text/javascript';
			script.id = 'loadScript';
			head.appendChild(script);
	}
	loadContent('http://www.google-analytics.com/ga.js');
	try {
		var pageTracker = _gat._getTracker("UA-8435065-3");
		pageTracker._trackPageview();
		pageTracker._trackPageview("/script/InventoryAnalyzer");
	}
	catch(err) {}
	//end analytics
}
)()
